package com.example.memo2.ui.calendar

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.memo2.R
import com.example.memo2.databinding.FragmentCalendarBinding
import com.example.memo2.ui.MemoViewModel
import com.example.memo2.ui.home.MemoAdapter
import com.example.memo2.ui.detail.MemoDetailActivity
import com.example.memo2.utils.MediaUtils
import com.google.android.material.snackbar.Snackbar
import java.util.*

class CalendarFragment : Fragment() {
    
    private var _binding: FragmentCalendarBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: MemoViewModel by activityViewModels()
    private lateinit var memoAdapter: MemoAdapter
    private lateinit var calendarAdapter: CalendarAdapter
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCalendarBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupCalendarView()
        setupMemoRecyclerView()
        observeData()
        
        // 设置默认选中今天
        val today = Date()
        viewModel.setSelectedDate(today)
    }
    
    private fun setupCalendarView() {
        calendarAdapter = CalendarAdapter { date ->
            viewModel.setSelectedDate(date)
        }
        
        binding.calendarRecyclerView.apply {
            adapter = calendarAdapter
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        }
        
        // 生成当前月份的日期
        generateCalendarDays()
    }
    
    private fun setupMemoRecyclerView() {
        memoAdapter = MemoAdapter(
            onItemClick = { memo ->
                // 跳转到详情页面
                val intent = Intent(requireContext(), MemoDetailActivity::class.java)
                intent.putExtra(MemoDetailActivity.EXTRA_MEMO_ID, memo.id)
                startActivity(intent)
            },
            onItemLongClick = { memo ->
                // 长按删除功能
                showDeleteConfirmDialog(memo)
                true
            }
        )
        
        binding.memosRecyclerView.apply {
            adapter = memoAdapter
            layoutManager = LinearLayoutManager(context)
        }
    }
    
    private fun observeData() {
        viewModel.selectedDate.observe(viewLifecycleOwner) { selectedDate ->
            // 更新选中状态
            calendarAdapter.setSelectedDate(selectedDate)
            
            // 获取选中日期的备忘录
            viewModel.getMemosByDate(selectedDate).observe(viewLifecycleOwner) { memos ->
                memoAdapter.submitList(memos)
                updateEmptyState(memos.isEmpty())
            }
            
            // 更新日期显示
            binding.selectedDateText.text = formatSelectedDate(selectedDate)
        }
    }
    
    private fun generateCalendarDays() {
        val calendar = Calendar.getInstance()
        val today = calendar.time
        
        // 生成前后各15天的日期
        calendar.add(Calendar.DAY_OF_YEAR, -15)
        val dates = mutableListOf<Date>()
        
        repeat(31) {
            dates.add(calendar.time)
            calendar.add(Calendar.DAY_OF_YEAR, 1)
        }
        
        calendarAdapter.submitList(dates)
        
        // 滚动到今天
        val todayPosition = dates.indexOfFirst { 
            Calendar.getInstance().apply { time = it }.get(Calendar.DAY_OF_YEAR) == 
            Calendar.getInstance().apply { time = today }.get(Calendar.DAY_OF_YEAR)
        }
        
        if (todayPosition != -1) {
            binding.calendarRecyclerView.scrollToPosition(todayPosition)
        }
    }
    
    private fun formatSelectedDate(date: Date): String {
        val calendar = Calendar.getInstance().apply { time = date }
        val today = Calendar.getInstance()
        
        return when {
            calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) && 
            calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) -> getString(R.string.today)
            
            calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) - 1 && 
            calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) -> getString(R.string.yesterday)
            
            calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1 && 
            calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) -> getString(R.string.tomorrow)
            
            else -> {
                val month = calendar.get(Calendar.MONTH) + 1
                val day = calendar.get(Calendar.DAY_OF_MONTH)
                getString(R.string.month_day_format, month, day)
            }
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        if (isEmpty) {
            binding.memosRecyclerView.visibility = View.GONE
            binding.emptyStateText.visibility = View.VISIBLE
        } else {
            binding.memosRecyclerView.visibility = View.VISIBLE
            binding.emptyStateText.visibility = View.GONE
        }
    }
    
    private fun showDeleteConfirmDialog(memo: com.example.memo2.data.model.Memo) {
        androidx.appcompat.app.AlertDialog.Builder(requireContext())
            .setTitle(getString(R.string.delete_confirm_title))
            .setMessage(getString(R.string.delete_confirm_message))
            .setPositiveButton(getString(R.string.action_confirm)) { _, _ ->
                deleteMemo(memo)
            }
            .setNegativeButton(getString(R.string.action_cancel), null)
            .show()
    }
    
    private fun deleteMemo(memo: com.example.memo2.data.model.Memo) {
        viewModel.deleteMemo(memo)
        
        // 删除相关的媒体文件
        MediaUtils.parseImagePaths(memo.imagePaths).forEach { imagePath ->
            MediaUtils.deleteFile(imagePath)
        }
        memo.audioPath?.let { audioPath ->
            MediaUtils.deleteFile(audioPath)
        }
        
        Snackbar.make(binding.root, getString(R.string.memo_deleted), Snackbar.LENGTH_SHORT).show()
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 